package com.chap6;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * <p>
 * <code>SemaphoreDemo</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-17 10:38
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
@Slf4j
public class SemaphoreDemo {
    //2 一次允许多少个线程同时请求
    private static Semaphore semaphore = new Semaphore(2);
    private static Executor executor =  Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            executor.execute(()->getProductInfo());
        }
    }

    //限流，抢不到资源的等待，后续都可以抢到资源，基本用法
    public static String getProductInfo(){
        try{
            semaphore.acquire();//申请许可
            log.info("请求服务");
            Thread.sleep(2000);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            semaphore.release();//释放许可
        }
        return "返回商品详情信息";
    }

    //限流，抢不到资源的直接返回提示信息
    public static String getProductInfo2(){
        if (!semaphore.tryAcquire()){
            log.error("请求被流控了");
            return "请求被流控了";
        }
        try{
            log.info("请求服务");
            Thread.sleep(2000);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            semaphore.release();
        }
        return "返回商品详情信息";
    }

}
